package com.bw.mallshop.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.bw.mallshop.timmer.TimeServiceThread;
import com.bw.mallshop.timmer.TimmerCallBack;
import com.bw.mallshop.timmer.TimmerHandler;

import java.lang.ref.WeakReference;

/**
 * Android 进程分类:
 * 前台进程:当前正在执行使用的进程
 * 可见进程：被透明进程遮挡的进程->使用进程A时突然来电话，屏幕上电话提醒遮挡A进程，
 * 但用户可以看到A进程界面，不能操作
 * 服务进程:当前进程中无界面，只有后台服务在运行(start)
 * 空进程：没有系统级组件在执行
 * 清理内存顺序:空，服务，可见，
 * */
public class TimeService extends Service implements TimmerCallBack {

    private long nowTime = 0;//服务后台维护的当前时间
    private TimeServiceThread thread;
    public void startTimmer(){
        thread = new TimeServiceThread(new TimmerHandler(this));
        thread.start();
    }

    public void setNowTime(long nowTime) {
        this.nowTime = nowTime;
    }

    public long getNowTime() {
        return nowTime;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new TimeBinder(this);
    }

    @Override
    public void onDestroy() {
        thread.interrupt();//传递终端信号进入timeservicethread线程
        super.onDestroy();
    }

    @Override
    public void timeCallBack(int time) {
        nowTime += time;
    }

    public static class TimeBinder extends Binder{

        private WeakReference<TimeService>weakReference;
        public TimeBinder(TimeService service){
            weakReference = new WeakReference<>(service);
        }

        public TimeService getService(){
            return weakReference.get();
        }
    }

}
